﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ArtMath.CommonType;

namespace ArtMath.Control
{
    public partial class ObjectSelector<T> : UserControl where T : IName
    {
        IList<T> oldSelectedObjects, newSelectedObjects;
        bool cancel;
        public ObjectSelector(IEnumerable<T> all, IList<T> selected)
        {
            InitializeComponent();
            foreach (T obj in all)
            {
                ListViewItem item = new ListViewItem(obj.Name) { Tag = obj };
                item.Checked = selected.Contains(obj);
                lvObjects.Items.Add(item);
            }
            oldSelectedObjects = newSelectedObjects = selected;
        }
        public ObjectSelector(IEnumerable<T> all, params string[] selectedObjectNames)
        {
            InitializeComponent();
            List<T> selected = new List<T>();
            foreach (T obj in all)
            {
                ListViewItem item = new ListViewItem(obj.Name) { Tag = obj };
                item.Checked = selectedObjectNames.Contains(obj.Name);
                lvObjects.Items.Add(item);
            }
            oldSelectedObjects = newSelectedObjects = selected;
        }
        private void ObjectSelector_Leave(object sender, EventArgs e)
        {
            if (!cancel)
            {
                T[] arr = new T[oldSelectedObjects.Count];
                oldSelectedObjects.CopyTo(arr, 0);
                newSelectedObjects = arr;
            }
        }

        public IList<T> NewSelectedObjects
        {
            get { return newSelectedObjects; }
        }
        public string NewSelectedObjectNames
        {
            get
            {
                if (NewSelectedObjects.Count == 0) return string.Empty;
                StringBuilder sb = new StringBuilder(NewSelectedObjects[0].Name);
                for (int i = 1; i < NewSelectedObjects.Count; i++)
                {
                    sb.Append(";" + NewSelectedObjects[i].Name);
                }
                return sb.ToString();
            }
        }
        private void lvObjects_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            T[] arr = new T[lvObjects.CheckedItems.Count];
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = (T)lvObjects.CheckedItems[i].Tag;
            }
            oldSelectedObjects = arr;
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                T[] arr = new T[newSelectedObjects.Count];
                newSelectedObjects.CopyTo(arr, 0);
                oldSelectedObjects = arr;
                cancel = true;
            }
            return base.ProcessDialogKey(keyData);
        }
    }
}
